<!--
 * @Author: your name
 * @Date: 2021-07-08 13:31:58
 * @LastEditTime: 2021-11-05 14:43:21
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \jinfeng_up\src\pages\overView\messageReminder.vue
-->
<template>
  <div class="messageReminder">
    <el-card>
      <!-- 消息提示标题区域 -->
      <div class="messageReminderHeader">
        <span>消息提醒</span>
        <el-button type="danger" @click="deleteAll" class="el-icon-delete deleteMessageItem rightDelete" size="mini">
          删除</el-button
        >
        <!-- <span  class="deleteMessageItem rightDelete"> <i class="el-icon-delete"></i> 删除</span> -->
      </div>

      <!-- TODO:

          messageOperate: "FeedbackAre"
          messageType: "OverView"
          两个枚举还有名字

       -->
      <div class="messageReminderWrap">
        <div class="messageReminderContent" v-for="(item, index) in messageList" :key="index">
          <div class="messageReminderContentArticle" @click="mouidleSkip(item)">
            <div class="titleAndType">
              <span class="aboutSeverity">{{ item.messageOperate | transferSeverity(MessageOperateEnum) }}</span>
              <span class="theme">{{ item.messageType | transferSeverity(MessageTypeEnum) }}</span>
            </div>

            <div class="messageTitle">{{ item.title }}</div>
          </div>
          <div class="messageReminderContentFooter">
            <div class="authorDate">
              <span>{{ item.userName }}</span>
              <span>|</span>
              <span>{{ item.releaseTime | resolvingDate }}</span>
              <span>|</span>
              <span class="deleteMessageItem" @click="deleteMessage(item.id)"><i class="el-icon-delete"></i></span>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>

  <!-- 需要引入的子组件:
                超期会议:overdueMeeting
                任务消息:taskMessage
  -->
</template>
<script>
import { OverView } from '@/api/overView/service'
const heartCheck = {
    timeout: 6000 * 1000,
    timer: null,
    serverTimer: null,
    reset() {
        this.timer && clearTimeout(this.timer)
        this.serverTimer && clearTimeout(this.serverTimer)
    },
    start(ws) {
        console.log('心跳检测')
        this.reset()
        this.timer = setTimeout(() => {
            // console.log('发送心跳,后端收到后，返回一个心跳消息')
            // onmessage拿到返回的心跳就说明连接正常
            ws.send(JSON.stringify({ heart: 1 }))
            this.serverTimer = setTimeout(() => {
                // 如果超过一定时间还没响应(响应后触发重置)，说明后端断开了
                ws.close()
            }, this.timeout)
        }, this.timeout)
    }
}
export default {
    name: '',
    components: {},
    props: {
        userInfo: {
            type: Object,
            default: () => {}
        },
        messageList: {
            type: Array,
            default: () => []
        }
    },
    data() {
        return {
            // // 登录人信息
            // userInfo: {},
            // // 消息列表
            // messageList: [],
            // Webscoket 通信服务路径地址
            wsuri: `ws://${process.env.VUE_APP_BASE_WEBSCOKET}/websocket/`, // ws wss
            lockReconnect: false, // 连接失败不进行重连
            maxReconnect: 5, // 最大重连次数，若连接失败
            socket: null,

            // 消息提醒操作类型枚举
            MessageOperateEnum: [
                {
                    title: '反馈激活',
                    value: 0
                },
                {
                    title: '反馈关闭',
                    value: 1
                },
                {
                    title: '反馈超期',
                    value: 2
                },
                {
                    title: '任务超期',
                    value: 3
                },
                {
                    title: '反馈严重超期',
                    value: 4
                },
                {
                    title: '影响类别',
                    value: 5
                },
                {
                    title: '任务严重超期',
                    value: 6
                },

                {
                    title: '任务激活',
                    value: 7
                },
                {
                    title: '反馈回退',
                    value: 8
                }
            ],

            // 消息类型枚举
            MessageTypeEnum: [
                {
                    title: '反馈',
                    value: 0
                },
                {
                    title: '任务',
                    value: 1
                }
            ]
        }
    },
    computed: {},
    watch: {},
    created() {},
    filters: {
    /**
     * @description:文字过滤器
     * @param {String} _val 传入的值
     * @param {Array} _list 定义的转换数组
     */
        transferSeverity(_val, _list) {
            let str = ''
            _list.findIndex(_item => {
                if (_item.value === _val) {
                    str = _item.title
                    return true
                } else {
                    return false
                }
            })
            return str
        },

        /**
     * @description: 时间格式过滤器
     * @param {Date} date 传入的时间值
     * @return {String} times 按照规则格式后的时间字符串
     */
        resolvingDate(date) {
            // date是传入的时间
            const d = new Date(date)

            const month = d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1
            const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate()
            const hours = d.getHours() < 10 ? '0' + d.getHours() : d.getHours()
            const min = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes()
            const sec = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds()

            const times = d.getFullYear() + '-' + month + '-' + day + ' ' + hours + ':' + min + ':' + sec

            return times
        }
    },

    mounted() {
    // this.getUserInfo()
    // /* 连接成功--获得消息 */
    // this.GetAllMessageListAsync()
    },
    destroyed() {},
    methods: {
    /**
     * @description: 获取当前登陆人信息 初始化Webscoket通信方法
     */
        async getUserInfo() {
            try {
                const result = await OverView.UserGetUserInfoAsync()
                if (result.success) {
                    this.userInfo = result.data
                    // this.initWebSocket()
                }
            } catch (err) {
                console.log(err)
            }
        },

        /**
     * @description: Webscoket 断线重连
     */
        reconnect() {
            if (this.lockReconnect || this.maxReconnect <= 0) {
                return
            }
            setTimeout(() => {
                // this.maxReconnect-- // 不做限制 连不上一直重连
                // this.initWebSocket()
            }, 20 * 1000)
        },

        /**
     * @description: 初始化Webscoket通信
     */
        initWebSocket() {
            try {
                if ('WebSocket' in window) {
                    this.wsuri = this.wsuri + this.userInfo.id
                    this.socket = new WebSocket(this.wsuri)
                    this.wsuri = `ws://${process.env.VUE_APP_BASE_WEBSCOKET}/websocket/`
                } else {
                    console.log('您的浏览器不支持websocket')
                }

                this.socket.onopen = this.websocketonopen
                this.socket.onerror = this.websocketonerror
                this.socket.onmessage = this.websocketonmessage
                this.socket.onclose = this.websocketclose
            } catch (e) {
                this.reconnect()
            }
        },

        /**
     * @description: Webscoket通信连接成功
     */
        websocketonopen() {
            console.log('WebSocket连接成功', this.socket.readyState)

            heartCheck.start(this.socket)
            // this.socket.send('发送数据')
            // this.websocketsend();
        },

        /**
     * @description: Webscoket通信连接失败
     */
        websocketonerror() {
            this.reconnect()
        },

        /**
     * @description: Webscoket通信接收到消息
     */
        websocketonmessage() {
            // console.log(e)
            // let data = JSON.parse(e.data);

            this.GetAllMessageListAsync()

            console.log('可以渲染网页数据...')
            // 消息获取成功，重置心跳
            heartCheck.start(this.socket)
        },

        /**
     * @description: Webscoket通信连接关闭
     * @param {Object} e 接收到的状态信息
     */
        websocketclose(e) {
            console.log('connection closed (' + e.code + ')')
            this.reconnect()
        },

        /**
     * @description: 客户端端向服务器发送信息
     */
        websocketsend() {
            const data = { answer: 'do something' }
            this.socket.send(JSON.stringify(data))
        },

        /**
     * @description: 获得当前登陆人所拥有的消息提醒 汇总
     */
        async GetAllMessageListAsync() {
            try {
                const result = await OverView.GetAllMessageListAsync()
                if (result.success) {
                    this.messageList = result.data
                    console.log('消息提醒信息', result.data)
                }
            } catch (err) {
                console.log(err)
            }
        },

        /**
     * @description: 确认删除消息提醒
     * @param {String} _id 主键ID
     */
        async DeleteMessageAsync(_id) {
            try {
                const result = await OverView.DeleteMessageAsync({ id: _id })
                if (result.success) {
                    this.GetAllMessageListAsync()
                    console.log('删除消息成功')
                }
            } catch (err) {
                console.log(err)
            }
        },
        async DeleteAllAsync() {
            try {
                const result = await OverView.DeleteAllAsync()
                if (result.success) {
                    this.$emit('GetAllMessageListAsync')
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    })
                } else {
                    this.$message({
                        type: 'error',
                        message: '删除失败'
                    })
                }
            } catch (err) {
                console.log(err)
            }
        },
        deleteAll() {
            this.$confirm('此操作将永久删除该消息提醒, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
            })
                .then(() => {
                    this.DeleteAllAsync()
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    })
                })
        },

        /**
     * @description: 删除消息提醒方法
     * @param {String} _val 主键ID
     * @return {*}
     */
        deleteMessage(_val) {
            this.$confirm('此操作将永久删除该消息提醒, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    this.DeleteMessageAsync(_val)
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    })
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    })
                })
        },

        /**
     * @description: 版块跳转 反馈详情
     * @param {Object} item 当前操作的板块对象
     */
        mouidleSkip(item) {
            if (item.messageType == '0') {
                this.$router.push({ path: 'Details?id=' + item.associatedId })
            } else if (item.messageType == '1') {
                this.$router.push({
                    path: 'taskDetail?id=' + item.associatedId
                })
            }
        }
    }
}
</script>

<style scoped lang="less">
.el-card {
  width: 100%;
  height: 100%;
  background: #ffffff;
  box-shadow: 0px 2px 5px 0px rgba(152, 160, 179, 0.2);
  border-radius: 5px;
  box-sizing: border-box;
  overflow-y: auto;
  /*滚动条样式*/
  &::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 8px;
    height: 8px;
  }
  &::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    background: #b2b8c0;
    border-radius: 5px;
    cursor: pointer;
  }
  &::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    border-radius: 0;
    background: transparent;
  }
}

.messageReminder {
  width: 100%;
  height: 815px;
  overflow-y: auto;
  overflow-x: hidden;
  position: relative;
  border-radius: 10px;
  ::v-deep .el-card__body {
    padding: 0;
  }
  .messageReminderContent {
    &:first-child {
      margin-top: 70px;
    }
  }
}
.messageReminderHeader {
  margin-bottom: 15px;
  width: 100%;
  box-sizing: border-box;
  position: absolute;
  padding: 20px 20px 10px 20px;
  background-color: #ffffff;
  box-shadow: 0 15px 3px -15px #333;
  .rightDelete {
    float: right;
    right: 20px;
  }
  span {
    font-size: 16px;
    font-weight: 400;

    &.deleteMessageItem {
      background-color: transparent;
      font-size: 14px;

      cursor: pointer;
      &:hover {
        color: red;
      }
    }
  }
}

.messageReminderContent {
  width: 100%;
  min-height: 82px;
  padding: 10px 20px;
  background: #ffffff;
  box-sizing: border-box;
  border: 1px solid #f2f1f1;
  border-radius: 10px;

  margin-bottom: 20px;

  .messageReminderContentArticle {
    width: 100%;
    font-size: 14px;
    font-weight: 400;
    color: #666666;
    // background-color: red;
    max-height: 40px;

    text-overflow: -o-ellipsis-lastline;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;

    .aboutSeverity {
      margin-right: 10px;
      font-weight: bold;
      font-size: 14px;
    }

    .titleAndType {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .theme {
        font-size: 12px;
        color: #999;
      }
    }
  }

  &:hover {
    box-shadow: 0px 5px 5px 0px rgba(152, 160, 179, 0.2);
    width: 100%;
    min-height: 82px;
    background: #ffffff;
    border: 1px solid #f2f1f1;
    box-sizing: border-box;
    padding: 10px 20px;
    color: #333333;

    border-radius: 10px;
  }

  .messageReminderContentFooter {
    margin-top: 10px;
    width: 100%;
    box-sizing: border-box;
    display: flex;
    justify-content: flex-end;
    font-size: 12px;
    font-weight: 400;
  }
  .authorDate {
    span {
      margin-left: 10px;
      &.deleteMessageItem {
        background-color: transparent;
        font-size: 14px;

        cursor: pointer;
        &:hover {
          color: red;
        }
      }
    }
  }
}

.messageReminderWrap {
  overflow: auto;
  width: 100%;
  box-sizing: border-box;
  border: 1px solid #ffffff;
  padding: 0 10px;

  /*滚动条样式*/
  &::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 5px;
    height: 32px;
  }
  &::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    background: #ccc;
    border-radius: 3px;
  }
  &::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    border-radius: 0;
    background: transparent;
  }
}
</style>
